<template>
  <GlobalBG title="工单详情" :showBack="true" :showCollege="false">
    <view class="work-order-detail">
      <view class="work-order-detail-contet">
        <!-- 工单基本信息模块，工单 ID 作为 header -->
        <uni-section
          :title="`工单 ID: ${workOrder.id || ''}`"
          class="section-base"
        >
          <view class="info-item">
            <text class="label">创建时间：</text>
            <text class="value">{{ workOrder.createTime || "--" }}</text>
          </view>
          <view class="info-item">
            <text class="label">派发时间：</text>
            <text class="value">{{ workOrder.dispatchTime || "--" }}</text>
          </view>
          <view class="info-item">
            <text class="label">分配人员：</text>
            <text class="value">{{ workOrder.assignPerson || "--" }}</text>
          </view>
          <view class="info-item">
            <text class="label">关联告警：</text>
            <text class="value">{{ workOrder.relatedAlarm || "--" }}</text>
          </view>
          <view class="info-item">
            <text class="label">故障描述：</text>
            <text class="value">{{ workOrder.faultDesc || "--" }}</text>
          </view>
        </uni-section>
        <!-- 处理信息模块 -->
        <uni-section title="">
          <uni-forms :model="formData" label-width="90">
            <uni-forms-item
              label="处理措施"
              class="select-popup"
              required
              :rules="[{ required: true, errorMessage: '请选择处理措施' }]"
            >
              <view
                class="action-section"
                @click="!isCompleted && handleMeasurePopup.open()"
                :style="{ pointerEvents: isCompleted ? 'none' : 'auto' }"
              >
                <text v-if="formData.handleMeasure">
                  {{
                    measureOptions.find(
                      (item) => item.value === formData.handleMeasure
                    )?.text
                  }}
                </text>
                <text v-else class="placeholder">请选择</text>
                <uni-icons
                  type="arrowright"
                  size="24"
                  color="#d7d7da"
                ></uni-icons>
              </view>
            </uni-forms-item>
            <uni-forms-item
              label="处理描述"
              class="textarea-desc"
              required
              :rules="[{ required: true, errorMessage: '请输入处理描述' }]"
            >
              <textarea
                v-model="formData.handleDesc"
                placeholder="请输入"
                :maxlength="1000"
                :disabled="isCompleted"
              ></textarea>
              <text class="count">{{ formData.handleDesc.length }}/1000</text>
            </uni-forms-item>
            <uni-forms-item label="" class="voice-input-forms-item">
              <VoiceInput
                :is-recording="isRecording"
                :temp-text="voiceTempText"
                @click="!isCompleted && startVoiceInput"
                :style="{ pointerEvents: isCompleted ? 'none' : 'auto' }"
              />
            </uni-forms-item>
          </uni-forms>
        </uni-section>
        <!-- 添加图片和视频模块 -->
        <uni-section title="">
          <uni-forms :model="formData" label-width="90">
            <uni-forms-item label="添加图片" class="module-img-video">
              <!-- 图片上传（使用默认限制） -->
              <ImageUpload
                @change="(files) => (formData.images = files)"
                :disabled="isCompleted"
              />
            </uni-forms-item>
            <uni-forms-item label="添加视频" class="module-img-video">
              <!-- 视频上传（使用默认限制） -->
              <VideoUpload
                @change="(files) => (formData.video = files)"
                :disabled="isCompleted"
              />
            </uni-forms-item>
          </uni-forms>
        </uni-section>
      </view>
      <view class="btn-group" v-if="showButtons">
        <button class="transfer-btn" @click="handleTransfer">转处理</button>
        <button class="submit-btn" @click="handleSubmit">提交</button>
      </view>
    </view>
  </GlobalBG>
  <!-- 处理措施弹框 -->
  <SelectPopup
    ref="handleMeasurePopup"
    :items="measureOptions"
    :value="formData.handleMeasure"
    @select="selectFaultType"
  />
  <ToOtherDeal ref="toOtherDealDialog" />
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref, onMounted } from "vue";
import ToOtherDeal from "@/components/ToOtherDeal.vue";
import api from "@/api/modules/home";

const receivedId = ref<string>("");
const tackleUserName = ref<string>("");

const workOrder = ref<any>({
  id: "",
  createTime: "",
  dispatchTime: "",
  assignPerson: "",
  relatedAlarm: "",
  faultDesc: "",
});
const measureOptions = ref([
  // { value: 1, text: "重启设备" },
  // { value: 2, text: "更换线缆" },
  // { value: 3, text: "软件升级" },
  // { value: 4, text: "远程调试" },
  // { value: 5, text: "现场维修" },
  // { value: 1, text: "重启设备" },
  // { value: 2, text: "更换线缆" },
  // { value: 3, text: "软件升级" },
  // { value: 4, text: "远程调试" },
  // { value: 5, text: "现场维修" },
]);
const formData = ref({
  handleMeasure: "",
  handleDesc: "",
  images: [],
  video: [],
  repairMan: "", // 新增维修人员字段
  repairDesc: "", // 新增维修描述字段
});
const rules = ref({
  handleMeasure: { required: true, message: "请选择处理措施" },
  handleDesc: { required: true, message: "请输入处理描述" },
  repairMan: { required: true, message: "请选择维修人员" }, // 新增验证规则
  repairDesc: { required: true, message: "请输入维修描述" }, // 新增验证规则
});
const handleMeasurePopup = ref();
const isCompleted = ref(false);

const selectFaultType = (item: { value: string; text: string }) => {
  formData.value.handleMeasure = item.value;
};

onLoad((options) => {
  if (options.id) {
    receivedId.value = options.id;
    console.log("接收到的 id:", receivedId.value);
    // 调用获取工单详情的函数，并传入 receivedId.value
    getWorkOrderDetail(receivedId.value);
  }
});

let currRow = ref();
const showButtons = ref(true);

const getWorkOrderDetail = async (id: string) => {
  try {
    const params = { uuid: id };
    console.log("请求参数:", params);
    let res = await api.workOrderGetById(params);
    console.log("获取工单详情", res);
    const data = res.data;
    workOrder.value = {
      id: data.work_order_code || "",
      createTime: data.create_time || "",
      dispatchTime: data.distribution_time || "",
      assignPerson: data.distribution_user_name || "",
      relatedAlarm: data.alarm_description || "",
      faultDesc: data.alarm_description || "",
    };

    if (data.status === "已完成") {
      showButtons.value = false;
      isCompleted.value = true;
    } else {
      showButtons.value = true;
      isCompleted.value = false;
    }
  } catch (error) {
    console.error("获取工单详情失败", error);
  }
};

// const handleSubmit = async () => {
//   try {
//   } catch (error) {
//     console.error("提交失败", error);
//   }
// };

// 提交处理
let formRef = ref();

const handleSubmit = async () => {
  try {

    if (!formData.value.handleMeasure || !formData.value.handleDesc) {
      uni.showToast({
        title: "数据不能为空，请填写处理措施和处理描述",
        icon: "none"
      });
      return;
    }
    const requestData = {
      tackle_measure: formData.value.handleMeasure, 
      tackle_description: formData.value.handleDesc,
      attachmentList: [...formData.value.images, ...formData.value.video],
      uuid: receivedId.value,
    };

    const res = await api.workOrderUpdateById(requestData);
    console.log("处理成功", res);
    uni.showToast({
      title: "处理成功",
      icon: "success",
    });
  } catch (error) {
    console.error("处理失败", error);
    uni.showToast({
      title: "处理失败，请重试",
      icon: "none",
    });
  }
};

let toOtherDealDialog = ref();
const handleTransfer = () => {
  // 实现转处理逻辑
  console.log("转处理", currRow.value);
  toOtherDealDialog.value.open(currRow.value);
};

const onFileChange = (field: string) => {
  // 处理文件选择变化逻辑
};

// 处理措施
const selectedAction = ref(null);
const showActionPopup = ref(false);

const selectAction = (action: any) => {
  selectedAction.value = action;
  showActionPopup.value = false;
};

// 语音输入
const isRecording = ref(false);
const voiceTempText = ref("");

// 在原来的代码中引入组件
import VoiceInput from "@/components/VoiceInput/VoiceInput.vue";

// 修改后的语音输入方法示例
const startVoiceInput = async () => {
  try {
    isRecording.value = true;
    // 调用语音识别API...
    // 识别过程中可以更新 voiceTempText.value
  } finally {
    isRecording.value = false;
  }
};

const goBack = () => {
  uni.navigateBack();
};

onMounted(async () => {
  try {
    const res = await api.baseapiDmListDm({ dm_sjdm: "tackle_measure_dict" });
    if (res.code === 0 && res.data) {
      measureOptions.value = res.data.map((item: any) => ({
        value: item.dm_bm,
        text: item.dm_mc,
      }));
    }
  } catch (error) {
    console.error("获取处理措施列表失败", error);
  }
});
</script>

<style lang="scss" scoped>
.work-order-detail {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f4f6fa;
  box-sizing: border-box;

  .work-order-detail-contet {
    flex: 1;
    overflow: auto;
  }

  .detail-header {
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: white;

    .back-btn {
      margin-right: 20px;
    }

    .title {
      font-size: 18px;
    }
  }

  :deep(.uni-section) {
    background: #ffffff;
    box-shadow: 0rpx 2rpx 8rpx 0rpx rgba(0, 12, 39, 0.06);
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    .uni-section-content {
      padding: 32rpx 30rpx;
    }
    .uni-section-header {
      padding: 0;
    }
    &.section-base {
      .uni-section-header {
        height: 75rpx;
        line-height: 75rpx;
        padding: 0;
        background: #5e93ff;
        padding-left: 40rpx;
        .uni-section__content-title {
          font-weight: 500;
          font-size: 30rpx !important;
          color: #ffffff !important;
        }
      }
    }
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    &:last-child {
      margin-bottom: 0;
    }
    .label {
      font-weight: 400;
      font-size: 30rpx;
      color: #333333;
      line-height: 42rpx;
    }

    .value {
      flex: 1;
      font-size: 28rpx;
      color: #666666;
    }
  }

  .uni-forms-item__label {
    width: 90px !important;
  }

  .action-section {
    width: 100%;
    height: 100%;
    text-align: right;
    align-items: center;
    display: flex;
    justify-content: flex-end;
  }
  .upload-tips {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  .module-img-video {
    padding-bottom: 100rpx;
    margin-bottom: 0;
    :deep(.uni-forms-item__content) {
      position: static;
    }
  }
}
</style>
